package com.zggk.lzz.xcbg;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.trace.LBSTraceClient;
import com.amap.api.trace.TraceListener;
import com.amap.api.trace.TraceLocation;
import com.blankj.utilcode.util.ToastUtils;
import com.zggk.lzz.R;
import com.zggk.lzz.adapter.LGRecycleViewAdapter;
import com.zggk.lzz.adapter.LGViewHolder;
import com.zggk.lzz.gj.GJ2Bean;
import com.zggk.lzz.gj.GJActivity;
import com.zggk.lzz.gj.GJBean;
import com.zggk.lzz.mvp.MVPBaseActivity;
import com.zggk.lzz.util.Utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.zggk.lzz.xcbg.XcbgContract.View;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class XcbgActivity extends MVPBaseActivity<View, XcbgPresenter> implements View ,AMap.OnMapLoadedListener{

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cancle_button)
    TextView cancleButton;
    @Bind(R.id.xcry_te)
    TextView xcryTe;
    @Bind(R.id.xcrq_te)
    TextView xcrqTe;
    @Bind(R.id.xcys_te)
    TextView xcysTe;
    @Bind(R.id.xcfw_re)
    RecyclerView xcfwRe;
    @Bind(R.id.xcjl_re)
    RecyclerView xcjlRe;
    @Bind(R.id.hbsm_te)
    TextView hbsmTe;
    @Bind(R.id.xclc_te)
    TextView xclcTe;
    @Bind(R.id.gj_te)
    TextView gjTe;
    @Bind(R.id.map)
    MapView mMapView;
    @Bind(R.id.activity_disease_new_scrollview)
    ScrollView activityDiseaseNewScrollview;
    @Bind(R.id.disease_new_parent_layout)
    RelativeLayout diseaseNewParentLayout;
    private List<String> XcfwDatas = new ArrayList<>();
    private LGRecycleViewAdapter<String> adapter;
    private LGRecycleViewAdapter<XcbgMxBean.DataBean.XcjlBean> adapter2;
    private List<XcbgMxBean.DataBean.XcjlBean> XcjlDatas = new ArrayList<>();
    private String ID;
    private AMap mAMap;
    private final static int AMAP_LOADED = 2;

    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_xcbg;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mMapView.onCreate(savedInstanceState);
        initView();
        initAdapter();
        initData();
    }

    private void initData() {
        mPresenter.getData(getIntent().getStringExtra("id"), XcbgActivity.this);
    }

    private void initAdapter() {
        xcfwRe.setHasFixedSize(true);
        xcfwRe.setNestedScrollingEnabled(false);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        xcfwRe.setLayoutManager(manager);
        adapter = new LGRecycleViewAdapter<String>(XcfwDatas) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_xcfw;
            }

            @Override
            public void convert(LGViewHolder holder, String zCDBean, int position) {
                holder.setText(R.id.lxbm_te, zCDBean);
                TextView deImg =(TextView) holder.getView(R.id.de_img);
                deImg.setVisibility(android.view.View.GONE);
            }
        };
        xcfwRe.setAdapter(adapter);
        xcjlRe.setHasFixedSize(true);
        xcjlRe.setNestedScrollingEnabled(false);
        LinearLayoutManager manager2 = new LinearLayoutManager(getContext());
        manager2.setOrientation(LinearLayoutManager.VERTICAL);
        xcjlRe.setLayoutManager(manager2);
        adapter2 = new LGRecycleViewAdapter<XcbgMxBean.DataBean.XcjlBean>(XcjlDatas) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_xcjl2;
            }

            @Override
            public void convert(LGViewHolder holder, XcbgMxBean.DataBean.XcjlBean zCDBean, int position) {
                holder.setText(R.id.lxbm_te, zCDBean.getResult());
            }
        };
        xcjlRe.setAdapter(adapter2);
    }

    private void initView() {
        setTitleText("巡查报告");
        goBack();
    }

    public static String getDateTimeFromMillisecond(String millisecond){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZ");
            Date date = new Date();
            try {
                date = sdf.parse(millisecond);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat sdf2=new SimpleDateFormat("HH:mm");
            String sDate=sdf2.format(date);
            return sDate;
    }

    public static String getDateTimeFromMillisecond2(String millisecond){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZ");
        Date date = new Date();
        try {
            date = sdf.parse(millisecond);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
        String sDate=sdf2.format(date);
        return sDate;
    }

    @Override
    public void getDatas(XcbgMxBean.DataBean dataBean) {
        xcrqTe.setText(getDateTimeFromMillisecond2(dataBean.getXcxq().get(0).getXcStartTime()));
        xcysTe.setText(getDateTimeFromMillisecond(dataBean.getXcxq().get(0).getXcStartTime()) + "-" + getDateTimeFromMillisecond(dataBean.getXcxq().get(0).getXcEndTime()));
        if (dataBean.getXcfw() != null && dataBean.getXcfw().size() > 0) {
            for (int i = 0; i < dataBean.getXcfw().size(); i++) {
                XcfwDatas.add(dataBean.getXcfw().get(i));
            }
        }
        if (XcfwDatas.size()==0){
            XcfwDatas.add("无法自动获取路线，请手动添加");
        }
        adapter.notifyDataSetChanged();

        if (dataBean.getXcjl() != null && dataBean.getXcjl().size() > 0) {
            for (int i = 0; i < dataBean.getXcjl().size(); i++) {
                XcjlDatas.add(dataBean.getXcjl().get(i));
            }
        }
        if (XcjlDatas.size()==0){
            XcbgMxBean.DataBean.XcjlBean xcjlBean =new  XcbgMxBean.DataBean.XcjlBean();
            xcjlBean.setResult("本次巡查未获取到相关上报事件");
            XcjlDatas.add(xcjlBean);
        }
        adapter2.notifyDataSetChanged();
        xcryTe.setText(dataBean.getXcxq().get(0).getUserName());
        hbsmTe.setText(dataBean.getXcxq().get(0).getRemark());
        xclcTe.setText(Utils.replaceNull(dataBean.getXcxq().get(0).getXclc()) + "km");
        ID = dataBean.getXcxq().get(0).getId();
        initMap();
    }

    private void initMap() {
        if (mAMap == null) {
            mAMap = mMapView.getMap();
            mAMap.setOnMapLoadedListener(this);
            mAMap.getUiSettings().setRotateGesturesEnabled(false);
            mAMap.getUiSettings().setTiltGesturesEnabled(false);
        }
    }

    @Override
    public void onMapLoaded() {
        Message msg = handler.obtainMessage();
        msg.what = AMAP_LOADED;
        handler.sendMessage(msg);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AMAP_LOADED:
//                    mPresenter.getLinDatas(getIntent().getStringExtra("id"),XcbgActivity.this);
//                    mPresenter.getLinDatas2(ID);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void getLinDatass(final List<GJBean.DataBean> JWD) {
        if (JWD.size() > 2) {
            List<TraceLocation> mGraspTraceLocationList = readLatLngs(JWD);
            LBSTraceClient mTraceClient = new LBSTraceClient(getApplicationContext());
            mTraceClient.queryProcessedTrace(1, mGraspTraceLocationList,
                    LBSTraceClient.TYPE_AMAP, new TraceListener() {
                        @Override
                        public void onRequestFailed(int i, String s) {
                            List<LatLng> points = readLatLngss(JWD);
                            mAMap.addPolyline(new PolylineOptions()
                                    .setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.grasp_trace_line))
                                    .width(30).addAll(points));
                            mAMap.addMarker(new MarkerOptions().position(
                                    points.get(0)).icon(
                                    BitmapDescriptorFactory.fromResource(R.drawable.start2)));
                            mAMap.addMarker(new MarkerOptions().position(
                                    points.get(points.size() - 1)).icon(
                                    BitmapDescriptorFactory.fromResource(R.drawable.end)));
                        }

                        @Override
                        public void onFinished(int i, List<LatLng> list, int i1, int i2) {
                            mAMap.addPolyline(new PolylineOptions()
                                    .setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.grasp_trace_line))
                                    .width(30).addAll(list));
                            LatLngBounds.Builder b = LatLngBounds.builder();
                            for (int x = 0; x < list.size(); x++) {
                                b.include(list.get(i));
                            }
                            mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(b.build(),
                                    50));
                            mAMap.addMarker(new MarkerOptions().position(
                                    list.get(0)).icon(
                                    BitmapDescriptorFactory.fromResource(R.drawable.start2)));
                            mAMap.addMarker(new MarkerOptions().position(
                                    list.get(list.size() - 1)).icon(
                                    BitmapDescriptorFactory.fromResource(R.drawable.end)));
                        }

                        @Override
                        public void onTraceProcessing(int i, int i1, List<LatLng> list) {
                        }

                    });
        }else {
            ToastUtils.showShort("该条巡查记录没有轨迹信息！");
        }
    }

    @Override
    public void getLinDatass2(List<List<GJ2Bean.DataBean>> datas) {
        for (int i = 0; i < datas.size(); i++) {
            List<GJ2Bean.DataBean> JWD =new ArrayList<>();
            JWD.addAll(datas.get(i));
            setRoad(JWD);
        }
    }
    private void setRoad(final List<GJ2Bean.DataBean> JWD) {
        if (JWD.size() > 2) {
            List<TraceLocation> mGraspTraceLocationList = readLatLngs2(JWD);
            LBSTraceClient mTraceClient = new LBSTraceClient(getApplicationContext());
            mTraceClient.queryProcessedTrace(1, mGraspTraceLocationList,
                    LBSTraceClient.TYPE_AMAP, new TraceListener() {
                        @Override
                        public void onRequestFailed(int i, String s) {
                            List<LatLng> points = new ArrayList<>();
                            points.add(new LatLng(Double.parseDouble(JWD.get(i).getLat()), Double.parseDouble(JWD.get(i).getLon())));
                            mAMap.addPolyline(new PolylineOptions().color(
                                    Color.RED).width(40).addAll(points));
                        }
                        @Override
                        public void onFinished(int i, List<LatLng> list, int i1, int i2) {
                            mAMap.addPolyline(new PolylineOptions().color(
                                    Color.RED).width(40).addAll(list));
                        }
                        @Override
                        public void onTraceProcessing(int i, int i1, List<LatLng> list) {
                        }
                    });
        }else {
            ToastUtils.showShort("该条巡查记录没有轨迹信息！");
        }
    }
    private List<TraceLocation> readLatLngs2(List<GJ2Bean.DataBean> JWD) {
        CoordinateConverter converter = new CoordinateConverter(getContext());
        List<TraceLocation> mGraspTraceLocationList = new ArrayList<>();
        for (int i = 0; i < JWD.size(); i++) {
            boolean isAMapDataAvailable = converter.isAMapDataAvailable(Double.parseDouble(JWD.get(i).getLat()), Double.parseDouble(JWD.get(i).getLon()));
            if (isAMapDataAvailable) {
                TraceLocation location = new TraceLocation();
                location.setBearing(0);
                location.setLatitude(Double.parseDouble(JWD.get(i).getLat()));
                location.setLongitude(Double.parseDouble(JWD.get(i).getLon()));
                location.setSpeed(0);
                location.setTime(0);
                mGraspTraceLocationList.add(location);
            }
        }
        return mGraspTraceLocationList;
    }
    private List<TraceLocation> readLatLngs(List<GJBean.DataBean> JWD) {
        CoordinateConverter converter = new CoordinateConverter(getContext());
        List<TraceLocation> mGraspTraceLocationList = new ArrayList<>();
        for (int i = 0; i < JWD.size(); i++) {
            boolean isAMapDataAvailable = converter.isAMapDataAvailable(Double.parseDouble(JWD.get(i).getJWData().getLat()), Double.parseDouble(JWD.get(i).getJWData().getLon()));
            if (isAMapDataAvailable) {
                TraceLocation location = new TraceLocation();
                location.setBearing(0);
                location.setLatitude(Double.parseDouble(JWD.get(i).getJWData().getLat()));
                location.setLongitude(Double.parseDouble(JWD.get(i).getJWData().getLon()));
                location.setSpeed(0);
                location.setTime(0);
                mGraspTraceLocationList.add(location);
            }
        }
        return mGraspTraceLocationList;
    }

    private List<LatLng> readLatLngss(List<GJBean.DataBean> JWD) {
        List<LatLng> points = new ArrayList<>();
        LatLngBounds.Builder b = LatLngBounds.builder();
        for (int i = 0; i < JWD.size(); i++) {
            points.add(new LatLng(Double.parseDouble(JWD.get(i).getJWData().getLat()), Double.parseDouble(JWD.get(i).getJWData().getLon())));
            b.include(points.get(i));
        }
        mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(b.build(),
                10));
        return points;
    }

    @OnClick({R.id.gj_te})
    public void onViewClicked(android.view.View view) {
        switch (view.getId()) {
            case R.id.gj_te:
                Intent intent = new Intent(XcbgActivity.this, GJActivity.class);
                intent.putExtra("id", ID);
                intent.putExtra("time", xcrqTe.getText().toString());
                intent.putExtra("xcr", xcryTe.getText().toString());
                startActivity(intent);
                break;
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
}
